package cn.xxy.result;

import cn.xxy.ResultSetHandler;
import cn.xxy.RowProcessor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author xxy
 * @date 2021/7/29
 */
public class KeyedHandler<K> extends  org.apache.commons.dbutils.handlers.AbstractKeyedHandler<K, Map<String, Object>> implements ResultSetHandler<Map<K,Map<String, Object>>> {

    private final int columnIndex;
    private final String columnName;

    public KeyedHandler() {
        this(1, (String)null);
    }

    public KeyedHandler(String columnName) {
        this(1, columnName);
    }
    public KeyedHandler(int columnIndex) {
        this(columnIndex, (String)null);
    }

    private KeyedHandler(int columnIndex, String columnName) {
        this.columnIndex = columnIndex;
        this.columnName = columnName;
    }

    protected K createKey(ResultSet resultSet) throws SQLException {
        return (K)(this.columnName == null ? resultSet.getObject(this.columnIndex) : resultSet.getObject(this.columnName));
    }

    protected Map<String, Object> createRow(ResultSet resultSet) throws SQLException {
        return resultSet.next() ? RowProcessor.toMap(resultSet) : null;
    }
}
